import http from './request.js'
/**
 * 微信登录获取code
 */
export function wxLogin() {
    return new Promise((resolve, reject) => {
        wx.login({
            timeout: 10000,
            success: (result) => {
                resolve(result);
            },
            fail: () => {
                reject(1);
            }
        });
    });
}

/**
 * 用户授权
 */
export function newAuthUser({
    code,
}) {
    let params = {
        code,
    }
    const tenantId  = wx.getStorageSync('tenantId')
    if(tenantId){
      params.tenantId = String(tenantId)
    }
    return http.post('user/oauth_user_shop', {
        ...params
    });
}

export const wxGetUserProfile = () => {
    return new Promise((resolve, reject) => {
        wx.getUserProfile({
            lang: 'zh_CN',
            desc: '业务需要',
            success: (result) => {
                resolve(result);
            },
            fail: (err) => {
                console.error(err)
                reject('');
            },
        });
    });
}

// 授权获取手机号
export function authGetPhone(paramObj) {
    return http.post('wxAuth/authPhone', {
        encryptedData: paramObj.encryptedData,
        iv: paramObj.iv,
    });
}



/**
 * 检查登录态
 */
export function chenkSesionAndLogin() {
    return new Promise((resolve, reject) => {
        wx.checkSession({
            success() {
                // console.log('session_key 未过期')
                resolve('success')
                //session_key 未过期，并且在本生命周期一直有效
            },
            fail() {
                // console.log('session_key 过期')

                // session_key 已经失效，需要重新执行登录流程
                wx.login({
                    timeout: 10000,
                    success: (result) => {
                        resolve(result);
                    },
                    fail: () => {
                        reject(1);
                    }
                });
            }
        })
    });
}

/**
 * 用户授权 信息
 */
export function fetchGetUserProfile(userInfo) {
 
    return http.post('user/editUser', userInfo);
}

/**
 * 获取最近一次用户访问的店铺id
 * @param {string} code wx.login()返回的code
 */
export function reqGetLastTenantId(code) {
  return http.get('user/getLastTenantId', {
    code,
  });
}


